import React, { useMemo, useState, useEffect } from 'react';
import styled from 'styled-components';
import { motion } from 'motion/react';
import './style.less';
import useDesignerStore from '@/store/Designer';
import { ColorPicker, Divider, Dropdown, Image, Input, Modal, Table, Tooltip } from 'antd';
import { ApartmentOutlined, BgColorsOutlined, BorderOutlined, CheckOutlined, ClearOutlined, DatabaseOutlined, DotChartOutlined, EditOutlined, FileMarkdownOutlined, FileOutlined, FullscreenOutlined, HeatMapOutlined, HolderOutlined, MacCommandOutlined, MenuOutlined, MinusOutlined, NumberOutlined, PlusOutlined, SaveOutlined, SettingOutlined, SkinOutlined, StopOutlined, TableOutlined, ZoomInOutlined, ZoomOutOutlined } from '@ant-design/icons';
import { BackgroundVariant, useEdges, useNodes, useReactFlow, useStore, useStoreApi } from '@xyflow/react';
import { useGraph } from '@/hooks/useGraph';
import { getFlowDataSources } from '@/api';
import { FileDetail } from './FileDetail';
import { useModelStore } from '@/store/MetaModel';
import MapPositionIcon from '../common/MiniMapIcon';

const ASide = styled.aside`
  user-select: none;
  background-color: #fff;
  border-radius: 10px;
  padding: 5px;
  height: 100%;
`

const Pointer = (props) => <div {...props}>
  <svg xmlns="http://www.w3.org/2000/svg" className="ed-svg-icon" viewBox="0 0 32 32" style={{ height: 32, width: 32, flex: '0 0 32px' }}>
    <path
      d="M13.057 23.583 11.291 9.538a.25.25 0 0 1 .4-.23l11.28 8.551a.25.25 0 0 1-.16.45l-2.738-.089a5.75 5.75 0 0 0-5.255 3.034l-1.293 2.416a.25.25 0 0 1-.468-.087Z"
      stroke="currentColor" strokeWidth="1" strokeLinejoin="round" fill=""></path>
  </svg>
</div>

const Hand = (props) => <div {...props}>
  <svg xmlns="http://www.w3.org/2000/svg" className="ed-svg-icon" viewBox="0 0 32 32"
    style={{ height: 32, width: 32, flex: '0 0 32px' }}>
    <path fillRule="evenodd" clipRule="evenodd"
      d="M24 18.25A6.75 6.75 0 0 1 17.25 25h-1.515a6.75 6.75 0 0 1-4.773-1.977l-3.36-3.36a2.185 2.185 0 0 1 2.898-3.261V11.75a2.25 2.25 0 0 1 3.079-2.092 2.251 2.251 0 0 1 4.177-.427A2.25 2.25 0 0 1 21 11.25v.377a2.25 2.25 0 0 1 3 2.122v4.5Zm-9-8a.75.75 0 0 1 1.5 0v5.5a.75.75 0 0 0 1.5 0v-4.5a.75.75 0 0 1 1.5 0v4.5a.75.75 0 0 0 1.5 0v-2a.75.75 0 0 1 1.5 0v4.5c0 2.9-2.35 5.25-5.25 5.25h-1.515a5.25 5.25 0 0 1-3.712-1.538l-3.36-3.359a.685.685 0 1 1 1.062-.852l.13.205c.625.982 2.145.54 2.145-.625V11.75a.75.75 0 0 1 1.5 0v4a.75.75 0 0 0 1.5 0v-5.5Z"
      fill="var(--file-icon--hand,#414142)"></path>
  </svg>
</div>

const ZoomIn = (props) => <Tooltip {...props} title='放大'>
  <ZoomInOutlined />
</Tooltip>
const ZoomOut = (props) => <Tooltip {...props} title='缩小'>
  <ZoomOutOutlined />
</Tooltip>
const Fullscreen = (props) => <Tooltip {...props} title='适应屏幕'>
  <BorderOutlined />
</Tooltip>

const ZoomState = ({ className }) => {
  const { zoomTo } = useReactFlow();
  const transform = useStore(s => s.transform[2])

  const handleZoom = (value) => {
    zoomTo(value / 100, { 'duration': 300 });
  };

  const zoom = Math.round(transform * 100)

  const items = [
    {
      label: '50%',
      key: 50,
      onClick: () => handleZoom(50)
    },
    {
      label: '75%',
      key: 75,
      onClick: () => handleZoom(75)
    },
    {
      label: '100%',
      key: 100,
      onClick: () => handleZoom(100)
    },
    {
      label: '150%',
      key: 150,
      onClick: () => handleZoom(150)
    },
    {
      label: '200%',
      key: 200,
      onClick: () => handleZoom(200)
    }
  ];

  const menu = {
    items
  };

  return <Dropdown menu={menu}>
    <div className={className}>{zoom}%</div>
  </Dropdown>;
}

const ColorDot = ({ color }) => (
  <span
    style={{
      display: 'inline-block',
      width: 12,
      height: 12,
      borderRadius: '50%',
      backgroundColor: color,
      marginRight: 8,
      verticalAlign: 'middle'
    }}
  />
);

const More = ({ className }) => {
  const { vluModelName } = useModelStore()
  const { background, primaryColor, setPrimaryColor, setBackground, miniMap, setMiniMap } = useDesignerStore()
  const nodes = useNodes()
  const edges = useEdges()
  const { setNodes, setEdges } = useReactFlow()

  const items = [
    {
      label: '文件信息',
      key: 'vluModelName',
      type: 'group',
      style: {
        fontSize: 12
      },
      children: [
        {
          itemIcon: <EditOutlined />,
          label: <div style={{
            maxWidth: '80%', overflow: 'hidden',
            textOverflow: 'ellipsis', display: '-webkit-box',
            WebkitLineClamp: 2, WebkitBoxOrient: 'vertical'
          }}>{vluModelName}</div>,
          onClick: (key) => {
            Modal.confirm({
              icon: null,
              title: <div style={{ fontSize: 14 }}>详细信息</div>,
              content: <FileDetail nodes={nodes} edges={edges} />,
              closable: true,
              maskClosable: true,
              footer: false,
              centered: true,
            })
          }
        },
      ],
      icon: <FileMarkdownOutlined />,
    },
    {
      type: 'divider'
    },
    {
      label: '偏好设置',
      key: 'skin',
      type: 'group',
      style: {
        fontSize: 12
      },
      icon: <SkinOutlined />,
      children: [
        {
          label: '主题色调',
          key: 'color',
          icon: <BgColorsOutlined />,
          onClick: ({ key }) => setPrimaryColor(key),
          children: [
            { key: 'china-red', name: '中国红', value: '#e60000' },
            { key: 'grass-green', name: '翡翠绿', value: '#00aa90' },
            { key: 'violet-purple', name: '罗兰紫', value: '#722ed1' },
            { key: 'golden-yellow', name: '帝王黄', value: '#faad14' },
            // ...其他颜色
          ].map(color => {
            return {
              key: color.value,
              itemIcon: color.value === primaryColor && <CheckOutlined />,
              style: {
                width: 200
              },
              label: (
                <span>
                  <ColorDot color={color.value} />
                  {color.name} {color.value}
                </span>
              )
            }
          })
        },
        {
          label: '画布背景',
          key: 'bg',
          icon: <MacCommandOutlined />,
          itemIcon: ({ eventKey }) => {
            return eventKey === background ? <CheckOutlined /> : null
          },
          onClick: ({ key }) => setBackground(key),
          children: [
            {
              key: 'hidden',
              label: '无背景',
              icon: <StopOutlined />,
              style: {
                width: 200
              }
            },
            {
              key: BackgroundVariant.Dots,
              label: '点状背景',
              icon: <HolderOutlined />,
              style: {
                width: 200
              }
            },
            {
              key: BackgroundVariant.Cross,
              label: '十字背景',
              icon: <PlusOutlined />
            },
            {
              key: BackgroundVariant.Lines,
              label: '网格背景',
              icon: <TableOutlined />
            }
          ]
        },
        {
          label: '地图位置',
          key: 'minimap',
          icon: <ApartmentOutlined />,
          itemIcon: ({ eventKey }) => {
            return eventKey === miniMap ? <CheckOutlined /> : null
          },
          onClick: ({ key }) => setMiniMap(key),
          children: [
            {
              key: 'hidden',
              label: "隐藏",
              icon: <MapPositionIcon position="hidden" />,
              style: { width: 200 },
            },
            {
              key: "bottom-left",
              label: "左下",
              icon: <MapPositionIcon position="bottom-left" />,
              style: { width: 200 },
            },
            {
              key: "bottom-center",
              label: "下中",
              icon: <MapPositionIcon position="bottom-center" />,
              style: { width: 200 },
            },
            {
              key: "bottom-right",
              label: "右下",
              icon: <MapPositionIcon position="bottom-right" />,
              style: { width: 200 },
            },
            {
              key: "top-left",
              label: "左上",
              icon: <MapPositionIcon position="top-left" />,
              style: { width: 200 },
            },
            {
              key: "top-center",
              label: "上中",
              icon: <MapPositionIcon position="top-center" />,
              style: { width: 200 },
            },
            {
              key: "top-right",
              label: "右上",
              icon: <MapPositionIcon position="top-right" />,
              style: { width: 200 },
            }
          ]
        },
      ]
    },
    {
      label: '清空画布数据',
      key: 'clear',
      icon: <ClearOutlined />,
      danger: true,
      onClick: () => {
        Modal.confirm({
          title: '清空画布',
          content: <div>确认清空画布数据？<br />
            <b>注意：</b>此操作不可逆，请谨慎操作</div>,
          onOk: () => {
            setNodes([])
            setEdges([])
          }
        })
      },
    },
  ];

  const menu = {
    items
  };
  return <Dropdown menu={menu} overlayStyle={{ width: 220 }} trigger='click' overlayClassName='AAA'>
    <Tooltip title='设置'>
      <MenuOutlined className={className} />
    </Tooltip>
  </Dropdown>
}

export default () => {
  const { cursor, setCursor, drawerHeight, setSelectedNodes } = useDesignerStore();
  const { fitView, zoomIn, zoomOut, getZoom } = useReactFlow();
  const store = useStoreApi()
  const graph = useGraph()

  const Cursor = cursor === 'pointer' ? Pointer : Hand
  const troggleCursor = () => {
    const isInteractive = cursor === 'pointer'
    store.setState({
      nodesDraggable: !isInteractive,
      nodesConnectable: !isInteractive,
      elementsSelectable: !isInteractive,
    });

    setCursor(cursor === 'pointer' ? 'hand' : 'pointer')
  }

  const handleFitView = () => {
    setSelectedNodes([])
    fitView({ duration: 300 })
  }

  const handleSave = () => {
    console.error(graph)
  }

  return (
    <ASide className="aside">
      <div className='op-list'>
        <Cursor className='op-item selected cursor' onClick={troggleCursor} />
        <Divider type="vertical" style={{ height: 20 }} />
        <ZoomOut className='op-item' onClick={() => {
          zoomOut({ duration: 300 });
        }} />
        <ZoomState className='op-item zoom-state' />
        <ZoomIn className='op-item' onClick={() => {
          zoomIn({ duration: 300 });
        }} />
        <Fullscreen className='op-item' onClick={handleFitView} />
        <SaveOutlined className='op-item' onClick={handleSave} />
        <Divider type="vertical" style={{ height: 20 }} />
        <More className='op-item' />
      </div>
    </ASide>
  );
};
